<template>
  <div class="Manage">
    <div class="page-head">
      <div class="page-title">设备管理</div>
      <div class="page-tool">
        
        <search-input placeholder="设备名称或CNC ID搜索" @search="searchChange" />
        <div
          class="tool-btn"
          @click="exportData"
        >
          模板下载
        </div>
        <div
          class="tool-btn"
        >
          <input
            type="file"
            class="file-input"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            ref="batch_update"
            @change="batchExcel($event, 'batch_update')"
          >
          批量更新
        </div>
        <div
          class="tool-btn"
        >
          <input
            type="file"
            class="file-input"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            ref="batch_import"
            @change="batchExcel($event, 'batch_import')"
          >
          批量导入
        </div>
        <div
          class="tool-btn"
          @click="open('add')"
        >
          新增设备
        </div>
      </div>
    </div>
    <div class="page-body">
      <div class="table_data">
        <el-table :data="tableData" stripe border :fit="true" :height="$tableHeight">
          <el-table-column
            prop="alias"
            :show-overflow-tooltip="true"
            label="设备名称"
          >
          </el-table-column>
          <el-table-column
            prop="cnc_id"
            label="CNC ID"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="cnc"
            width="100"
            label="CNC类型"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="{ row }">
              <div>
                {{cncSel.find(s => s.k == row.cnc).v}}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column
            width="60"
            :show-overflow-tooltip="true"
            prop="floor"
            label="楼层"
          >
          </el-table-column>
          <el-table-column
           width="60"
            :show-overflow-tooltip="true"
            label="车间"
            prop="branch"
          >
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="line"
            label="条线"
            width="60"
          >
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="seq"
            label="序号"
            width="60"
          >
          </el-table-column>

          <el-table-column
            width="140"
            :show-overflow-tooltip="true"
            prop="serial"
            label="设备识别号"
          >
          </el-table-column>
          <el-table-column
            width="80"
            :show-overflow-tooltip="true"
            label="端口号"
            prop="port"
          >
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="username"
            label="用户名"
          >
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="password"
            label="密码"
          >
          </el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template slot-scope="{ row }">
              <div class="operation-col">
                <div
                  class="txt-btn ope-btn"
                  @click="open('update', row)"
                >
                  <el-tooltip effect="dark" content="修改" placement="top-start">
                    <img src="~assets/img/edit.png" alt="">
                  </el-tooltip>
                </div>
                <div
                  class="txt-btn"
                  @click="doDelete(row)"
                >
                  <el-tooltip effect="dark" content="删除" placement="top-start">
                    <img src="~assets/img/delete.png" alt="">
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-footer">
        <pagina-tion
          class="page-pager"
          v-show="total >= 0"
          :background="true"
          :total="total"
          :offset.sync="offset"
          :limit.sync="limit"
          @pagination="getChangePage"
          @sizeChange="getSizePage"
        />
      </div>
    </div>

    <!-- 新增和修改弹框 -->
    <el-dialog
      :visible.sync="model.visible"
      width="370px"
      :title="model.type === 'add' ? '新增设备' : '修改设备'"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="dialog-body">
        <el-form
          ref="form"
          :model="form"
          label-width="110px"
          label-position="left"
        >
          <el-form-item label="楼层" class="required">
            <el-input
              name="floor"
              placeholder="请输入楼层"
              v-model="form.floor"
              v-validate="'required'"
            />
            <div v-show="errors.has('floor')" class="el-form-item__error">
              {{ errors.first("floor") }}
            </div>
          </el-form-item>
          <el-form-item label="车间" class="required">
            <el-input
              name="branch"
              placeholder="请输入车间"
              v-model="form.branch"
              v-validate="'required'"
            />
            <div v-show="errors.has('branch')" class="el-form-item__error">
              {{ errors.first("branch") }}
            </div>
          </el-form-item>
          <el-form-item label="条线" class="required">
            <el-input
              name="line"
              placeholder="请输入条线"
              v-model="form.line"
              v-validate="'required'"
            />
            <div v-show="errors.has('line')" class="el-form-item__error">
              {{ errors.first("line") }}
            </div>
          </el-form-item>
          <el-form-item label="序号" class="required">
            <el-input
              name="seq"
              placeholder="请输入序号"
              v-model="form.seq"
              v-validate="'required'"
            />
            <div v-show="errors.has('seq')" class="el-form-item__error">
              {{ errors.first("seq") }}
            </div>
          </el-form-item>
          <el-form-item label="设备名称" class="required">
            <el-input
              name="aliasName"
              placeholder="请输入设备名称"
              v-model="getAlias"
              :disabled="true"
            />
          </el-form-item>
          <el-form-item label="CNC类型" label-position="left" class="required">
            <el-select
              v-model="form.cnc"
              name="cnc_name"
              placeholder="请选择CNC类型"
              v-validate="'required'"
            >
              <el-option
                v-for="item in cncSel"
                :key="item.k"
                :label="item.v"
                :value="item.k">
              </el-option>
            </el-select>
            <div
              v-show="errors.has('cnc_name')"
              class="el-form-item__error"
            >
              {{ errors.first("cnc_name") }}
            </div>
          </el-form-item>

          <el-form-item label="设备识别号" class="required">
            <el-input
              v-model="form.serial"
              name="serial"
              v-validate="'required|serial'"
              placeholder="请输入设备识别号"
            ></el-input>
            <div class="form-item-tip">
              可填写设备序列号、IP地址或Mac地址
            </div>
            <div v-show="errors.has('serial')" class="el-form-item__error">
              {{ errors.first("serial") }}
            </div>
          </el-form-item>
          
          
          <el-form-item label="端口号" class="required">
            <el-input
              v-model="form.port"
              name="port"
              v-validate="'required'"
              placeholder="请输入端口号"
            ></el-input>
            <div v-show="errors.has('port')" class="el-form-item__error">
              {{ errors.first("port") }}
            </div>
          </el-form-item>
                    
          <el-form-item label="用户名" class="required">
            <el-input
              v-model="form.username"
              name="username"
              v-validate="'required'"
              placeholder="请输入用户名"
            ></el-input>
            <div v-show="errors.has('username')" class="el-form-item__error">
              {{ errors.first("username") }}
            </div>
          </el-form-item>
                    
          <el-form-item label="密码" class="required">
            <el-input
              v-model="form.password"
              name="password"
              v-validate="'required'"
              placeholder="请输入密码"
            ></el-input>
            <div v-show="errors.has('password')" class="el-form-item__error">
              {{ errors.first("password") }}
            </div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">保 存</el-button>
      </span>
    </el-dialog>

    <!-- 删除弹窗 -->
    <el-dialog
      :visible.sync="visibility"
      width="430px"
      height="100px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico" src="~assets/img/warning.png" />
        <div class="comfirm-txt">
          <div>确定删除该条数据？</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visibility = false">取 消</el-button>
        <el-button type="primary" @click="asyncDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { format } from "silly-datetime";
import * as api from "@/api";
import { limit, smallLimit } from "@/consts/consts";
import { readExcel } from "@/utils/excel";
import { downLoadFile } from "@/utils/tool";
import { manageKey } from "@/consts/formKey";
import searchInput from "@/components/libs/searchInput";
import paginaTion from "@/components/libs/paginaTion";


export default {
  components:{
    searchInput,
    paginaTion
  },
  data() {
    return {
      limit,
      total: 0,
      offset: 0,
      tableData: [],
      format,
      search: "",
      cncSel: [],
      model: {
        type: "add",
        visible: false,
      },
      id: '',
      form: {
        ...manageKey
      },
      visibility: false,
      detailVisable: false,

    }
  },
  computed: {
    getAlias() {
      let { floor, branch, line, seq } = this.form
      return `${floor}-${branch}-${line}-${seq}`
    }
  },

  methods: {
    open(type, row = null) {
      this.$validator.reset();
      this.model.type = type;
      if (row) {
        for (const k in manageKey) {
          this.form[k] = row[k];
        }
        this.id = row.hub_id;
      }

      this.model.visible = true;
    },

    openDetail(row) {
      this.detail = row;
      this.detailVisable = true;
    },

    closeDetail() {
      this.detail = {};
      this.detailVisable = false;
    },

    getChangePage(val) {
      this.offset = val.offset;
      this.getList();
    },

    getSizePage(val) {
      this.offset = 0
      this.getList();
    },

    searchChange(e) {
      this.search = e;
      this.offset = 0;
      this.getList();
    },

    close() {
      this.model.visible = false;
      this.form = { ...manageKey };
    },

    submit() {
      this.$validator.validateAll().then((valid) => {
        if (valid) {
          this.addOrEdit();
        } else {
          this.$message.warning("有信息未填写正确");
        }
      });
    },

    
    doDelete(row) {
      this.id = row.hub_id
      this.visibility = true
    },

    batchExcel(e, fn) {
      let file = this.$refs[fn].files[0];
      let index = file.name.lastIndexOf(".")
      let suf = file.name.substr(index+1)
      const typeOk = ['xlsx'].includes(suf)
      if (typeOk) {
        readExcel(e, file, this[fn])
      }
      this.$refs[fn].value=''
    },

    // 模板下载
    async exportData() {
      const res = await api.manage(this).exportData()
      downLoadFile(res, `设备管理模板.xlsx`)
    },

    
    // 批量更新
    async batch_update(arr) {
      const { code } = await api.manage(this).batch_update({
        hub: arr
      });
      if (code === 0) {
        this.$message.success('操作成功')
        this.getList()
      }
    },
        
    // 批量导入
    async batch_import(arr) {
      const { code } = await api.manage(this).batch_import({
        hub: arr
      });
      if (code === 0) {
        this.$message.success('操作成功')
        this.getList()
      }
    },

            
    // 下拉列表
    async downList(type) {
      const { code, data } = await api.dropdown(this).downList({
        type
      })
      if (code === 0) {
        this[`${type}Sel`] = data
      }
    },

    // 列表
    async getList() {
      const { code, data, total } = await api.manage(this).getList({
        offset: this.offset,
        limit: this.limit,
        name: this.search,
      });
      if (code === 0) {
        this.tableData = data
        this.total = total
      }
    },


    async addOrEdit() {
      let fn = this.model.type
      this.form.alias = this.getAlias
      const { code } = await api.manage(this)[fn](this.form, this.id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.close();
        this.getList();
      }
    },

    async asyncDelete() {
      const { code } = await api.manage(this).delete(this.id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.id = "";
        this.visibility = false;
        if (this.total % this.limit === 1) {
          if (this.offset >= this.limit) {
            this.offset -= this.limit;
          }
        }
        this.getList();
      }
    },

  },
  created() {
    this.downList('cnc')
    this.getList();
  },
};
</script>

<style lang="stylus">
.Manage {

}

</style>